package cn.cmcc.online.smsapi.sdk.db.entity;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.ContentValues;
import cn.cmcc.online.smsapi.sdk.constant.Constant;
import cn.cmcc.online.smsapi.sdk.db.DBManager;
import cn.cmcc.online.smsapi.sdk.db.XyCursor;
import cn.cmcc.online.smsapi.sdk.db.base.BaseManager;
import cn.cmcc.online.smsapi.sdk.log.LogManager;
import cn.cmcc.online.smsapi.sdk.util.DateUtils;
import cn.cmcc.online.smsapi.sdk.util.StringUtils;

public class RecordActionManager {

    public static final String SCENE_ID = "scene_id";// 情景号

    public static final String DATE = "date";// 日期

    public static final String ACTION_TYPE = "action_type";// 操作按钮类型
    /* SDK-376 mobaohua 20160331 start */
    public static final String ACTION_CODE = "action_code";// 操作按钮类型
    /* SDK-376 mobaohua 20160331 end */
    public static final String TIMES = "times";// 次数

    public static final String TABLE_NAME = "tb_button_action_scene";

    public static final String DROP_TABLE = " DROP TABLE IF EXISTS "
            + TABLE_NAME;

    public static final String CREATE_TABLE = "create table  if not exists "
            + TABLE_NAME + " ("

            + SCENE_ID + " TEXT, " + DATE + " TEXT, " + ACTION_TYPE
            /* SDK-376 mobaohua 20160331 start */
            + " INTEGER DEFAULT '0', " + TIMES + " INTEGER DEFAULT '0', " + ACTION_CODE
            + " TEXT " + " ) ";
    
    public static final String ADD_ACTION_CODE = "ALTER TABLE " + TABLE_NAME
            + " ADD COLUMN " + ACTION_CODE + " TEXT";

    public static final String UPDATE_ACTION_CODE = " UPDATE " + TABLE_NAME
            + " SET " + ACTION_CODE + " = " + ACTION_TYPE
            + " WHERE "
            + ACTION_CODE + " = '' OR "+ACTION_CODE+" IS NULL";

    private static String[] mColumns = new String[] { SCENE_ID, DATE, ACTION_TYPE, TIMES, ACTION_CODE };
    /* SDK-376 mobaohua 20160331 end */
    
    //根据情景号，日期查询相关项
    public static JSONArray queryByIdDate(String scene_id,
            String date) {
        JSONArray buttonActionArr = null;
        XyCursor cur = null;
        try {
            cur = DBManager.query(TABLE_NAME,mColumns, SCENE_ID + " = ? and " + DATE
                    + " = ? ", new String[] { scene_id, date }, null, null,
                    null, null);
            buttonActionArr = BaseManager.loadArrDataFromCursor(mColumns, cur);
        } catch (Throwable e) {
//            e.printStackTrace();
            /*SDK-550 hewengao 20160719 start*/
            LogManager.w(Constant.TAG, "queryByIdDate: ", e);
            /*SDK-550 hewengao 20160719 end*/
        } finally {
            XyCursor.closeCursor(cur, true);
        }
        return buttonActionArr;
    }

    //查询某个情景号下的类型数据
    /* SDK-376 mobaohua 20160331 start */
    public static JSONObject queryInfoBySceneId(String scene_id, String type) {
        XyCursor cur = null;
        JSONObject info = null;
        String date = DateUtils.getCurrentTimeString("yyyyMMdd");
        try {
            cur = DBManager.query(TABLE_NAME,mColumns, SCENE_ID + " = ? and " + DATE
                    + " = ? and (" + ACTION_TYPE + " = ? or "  + ACTION_CODE + " = ? )", new String[] {
                    scene_id, date, type, type}, null, null, null, "1");
            /* SDK-376 mobaohua 20160331 end */
            info = BaseManager.loadSingleDataFromCursor(mColumns,cur);
        } catch (Throwable e) {
//            e.printStackTrace();
            /*SDK-550 hewengao 20160719 start*/
            LogManager.w(Constant.TAG, "queryInfoBySceneId: ", e);
            /*SDK-550 hewengao 20160719 end*/
        } finally {
            XyCursor.closeCursor(cur, true);
        }
        return info;
    }

    //插入或更新
    public static long insertOrUpdateParse(HashMap<String, String> paramsMap) {
        String scene_id = paramsMap.get("titleNo");
        String typeStr = paramsMap.get("type");
        /* SDK-376 mobaohua 20160331 start */
        String type = "-1";
        if (!StringUtils.isNull(typeStr)) {
            type = typeStr.trim();
        }
        /* SDK-376 mobaohua 20160331 end */
        long result = -1;
        JSONObject info = null;
        ContentValues values = null;

        try {
            /* SDK-376 mobaohua 20160331 start */
            if (!StringUtils.isNull(scene_id) && !"-1".equals(type)) {
                info = queryInfoBySceneId(scene_id, type);
            }

            if (info != null) {
                int times = Integer.parseInt(info.getString(TIMES));
                times += 1;
                info.put(TIMES, String.valueOf(times));
                values = BaseManager.getContentValues(values, false, info, mColumns);
                // 更新点击次数
                
                DBManager.update(TABLE_NAME, values, SCENE_ID + " = ? and "
                        + DATE + " = ? and " + ACTION_TYPE + " = ? and " + ACTION_CODE + " = ? ",
                        new String[] { info.getString(SCENE_ID), info.getString(DATE),
                            info.getString(ACTION_TYPE), info.getString(ACTION_CODE)});
                return 0;
            } else {

                String date = DateUtils.getCurrentTimeString("yyyyMMdd");
                // 插入一条记录
                values = BaseManager.getContentValues(null, SCENE_ID, scene_id, DATE, date,
                        ACTION_CODE, type, TIMES, "1");
                result = DBManager.insert(TABLE_NAME, values);

            }
            /* SDK-376 mobaohua 20160331 end */
        } catch (Throwable e) {
//            e.printStackTrace();
            /*SDK-550 hewengao 20160719 start*/
            LogManager.w(Constant.TAG, "insertOrUpdateParse: ", e);
            /*SDK-550 hewengao 20160719 end*/
        } finally {
        }
        return result;
    }

    public static void deleteAll() {
        try {
            DBManager.delete(TABLE_NAME, null, null);
        } catch (Throwable e) {
//            e.printStackTrace();
            /*SDK-550 hewengao 20160719 start*/
            LogManager.w(Constant.TAG, "deleteAll: ", e);
            /*SDK-550 hewengao 20160719 end*/
        }
    }

    public static void deleteInfoByDate(String date) {
        try {
            DBManager.delete(TABLE_NAME, DATE + " < ?", new String[] { date });
        } catch (Throwable e) {
//            e.printStackTrace();
            /*SDK-550 hewengao 20160719 start*/
            LogManager.w(Constant.TAG, "deleteInfoByDate: ", e);
            /*SDK-550 hewengao 20160719 end*/
        }
    }
    //获取每个情景号下的服务使用数据
    public static Map<String, String> queryActionRecord() {
        Map<String, String> actionRecord = null;
        String sceneId = "";
        String type = "";
        String count = "";
        XyCursor cur = null;
        try {
            //根据类型排序
            /* SDK-376 mobaohua 20160331 start */
            cur = DBManager.query(TABLE_NAME, mColumns, null, null, null, null, ACTION_CODE, null);
            if(cur == null){
                return null;
            }
            actionRecord = new HashMap<String, String>();
            while(cur.moveToNext()){
                //第一个字段为情景号
                sceneId = cur.getString(0);
                //将服务类型和服务次数拼接
                type = StringUtils.getTwoDigitType(cur.getString(4));
                /* SDK-376 mobaohua 20160331 end */

                count = StringUtils.getTwoDigitType(cur.getString(3));

                if(actionRecord.containsKey(sceneId)){
                    String value = actionRecord.get(sceneId);
                    actionRecord.put(sceneId, value + type + count);
                }else{
                    //第一个类型为type="00"-"短信识别"，不加入到结果
                    actionRecord.put(sceneId, count);
                }
            }
        } catch (Throwable e) {
//            e.printStackTrace();
            /*SDK-550 hewengao 20160719 start*/
            LogManager.w(Constant.TAG, "queryActionRecord: ", e);
            /*SDK-550 hewengao 20160719 end*/
        } finally {
            XyCursor.closeCursor(cur, true);
        }
        return actionRecord;
    }
}
